import {IStoreGoodsPageRow} from "@/api/modules/pointsMall";

interface IAddGoodsState {
  allSelected: IStoreGoodsPageRow[],
  waitingAddList: IStoreGoodsPageRow[],
}

export default {
  namespaced: true,
  state() {
    return {
      allSelected: [],
      waitingAddList: [],
    }
  },

  mutations: {
    // 记录已选择
    addSelected(state: IAddGoodsState, payload: IStoreGoodsPageRow) {
      const allSelected = [...state.allSelected]
      allSelected.push(payload)
      state.allSelected = allSelected
    },

    // 删除已选择
    deleteSelected(state: IAddGoodsState, payload: number) {
      const allSelected = [...state.allSelected]
      allSelected.splice(payload, 1)
      state.allSelected = allSelected
    },

    // 清空已选择
    removeSelected(state: IAddGoodsState) {
      state.allSelected = []
    },

    // 从现有列表 恢复 已选择
    recoverSelected(state: IAddGoodsState, payload: IStoreGoodsPageRow[]) {
      state.allSelected = [...payload]
    },

    // 将已选择的商品合并到待新增的列表中
    mergeSelectedToWaitingAddList(state: IAddGoodsState, selectedRows: IStoreGoodsPageRow[]) {
      const {waitingAddList} = state
      // 选中集合 和 全部已选集合的 差集 为新增，执行添加
      selectedRows.forEach(row => {
        const target = waitingAddList.find(item => row.storeProductId === item.storeProductId)
        if (!target) {
          waitingAddList.push(row)
        }
      })

      // 未选中集合 和 全部已选集合的 交集 为删除，执行删除
      const unselectedRows = waitingAddList.filter(item => !selectedRows.find(row => row.storeProductId === item.storeProductId))
      unselectedRows.forEach(row => {
        const targetIndex = waitingAddList.findIndex(item => item.storeProductId === row.storeProductId)
        if (targetIndex > -1) {
          waitingAddList.splice(targetIndex, 1)
        }
      })
    },

    // 删除待新增列表中的行
    deleteWaitingAddRow(state: IAddGoodsState, row: IStoreGoodsPageRow) {
      const {waitingAddList} = state
      const targetIndex = waitingAddList.findIndex(item => item.storeProductId === row.storeProductId)

      waitingAddList.splice(targetIndex, 1)
    },

    // 清空待新增商品
    removeWaitingAddList(state: IAddGoodsState) {
      state.waitingAddList = []
    }
  }
}
